package xorm

//http://xorm.topgoer.com/

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"

	"github.com/mitchellh/mapstructure"
	"github.com/xormplus/xorm/names"
	"log"
	"time"
)

//定义orm引擎
var x *xorm.Engine

//创建orm引擎
func init() {
	var err error
	x, err = xorm.NewEngine("mysql", "root:fan1988@tcp(127.0.0.1:3306)/godbc?charset=utf8")

	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}
	x.SetMapper(names.GonicMapper{})
	x.ShowSQL(true) //则会在控制台打印出生成的SQL语句；
	//if err := x.Sync(new(SysAccount)); err != nil {
	//	log.Fatal("数据表同步失败:", err)
	//}

	//全局拦截
	x.Before(func(i interface{}) {
		log.Println("--------------------", i)

	})
	x.After(func(i interface{}) {
		log.Println("--------------------", i)
	})
}

//增
func InsertReturnId() (affected int64, id interface{}) {
	user := SysAccount{
		UserName:   "taotao",
		Password:   "532542523",
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}
	affected, err := x.Insert(user)
	id = user.ID
	fmt.Println("*****", affected, id)

	if err == nil {
		return affected, id
	} else {
		panic(err)
	}
}

//删
func Del(id int64) {
	x.ID(id).Delete(&SysAccount{})
}

//改
func update(id int64, user *SysAccount) bool {
	affected, err := x.ID(id).Update(user)
	if err != nil {
		log.Fatal("错误:", err)
	}
	if affected == 0 {
		return false
	}
	return true
}

//查
func getinfo(id int64) *SysAccount {
	user := &SysAccount{ID: id}
	is, _ := x.Get(user)
	if !is {
		log.Fatal("搜索结果不存在!")
	}

	x.Query()
	return user
}

//TODO
func queryPage(){

}


func rawSql(){
	reuslts, _ := x.QueryInterface("select * from user where id=? limit 1",7)
	for _, record := range reuslts {
		for key, val := range record {
			fmt.Println(key, val)
		}
	}
	//这里的results是map可以用mapstructure库将通用的map[string]interface{}解码到对应的 Go 结构体中
	//go get github.com/mitchellh/mapstructure

	u := &SysAccount{}
	mapstructure.Decode(reuslts, u)

	updateSql := "update `user` set name=? where id=?"
	res, _ := x.Exec(updateSql, "ldj", 1)
	fmt.Println(res.RowsAffected())
}

func rowsScan() {
	u := &SysAccount{}
	rows, _ := x.Where("age > ? and age < ?", 12, 30).Rows(u)
	defer rows.Close()

	for rows.Next() {
		rows.Scan(u)

		fmt.Println(u)
	}
}

func RunXorm() {
	//InsertReturnId()

	rawSql()
}
